package com.llxz.blog.acl.controller;

import com.llxz.blog.acl.entity.User;
import com.llxz.blog.acl.service.UserService;
import com.llxz.blog.basic.exceptionhandler.MyException;
import com.llxz.blog.util.IpUtil;
import com.llxz.blog.util.JwtUtils;
import com.llxz.blog.util.MD5Utils;
import com.llxz.blog.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by IntelliJ IDEA.
 *
 * @author xzs
 * @description: date: 2021/9/4 9:34
 */
@RestController
@RequestMapping("/acl")
public class LoginController {

    @Autowired
    UserService userService;



    @PostMapping("login")
    public R login(@RequestBody User user){
        //从数据库中取出用户信息
        User result = userService.selectByUsername(user.getUsername());
        // 判断用户是否存在
        if (null == result){
            throw new MyException(2001,"用户名不存在");
        }
        //判断密码
        if (!MD5Utils.encrypt(user.getPassword()).equals(result.getPassword())){
            throw new MyException(2001,"密码错误");
        }
        //登录成功
        String jwtToken = JwtUtils.createJwtToken(result.getId(),result.getUsername());

        return R.ok().data("token",jwtToken);
    }

    @GetMapping("info")
    public R info(@RequestParam String token){
        boolean b = JwtUtils.checkToken(token);
        if (b)
            return R.ok().data("roles","管理员").data("name","admin").data("avatar","https://online-edu-zzm.oss-cn-beijing.aliyuncs.com/cat.jpeg");
        else
            return R.error().message("token 验证失败");
    }

    @PostMapping("logout")
    public R logout(){
        return R.ok();
    }
}

